<script lang="ts" setup>
import { useRoute } from "vue-router";
import {
	comment,
	getCommentById,
	deleteCommentById,
} from "@/api/comment/comment";
import { getThingInfoById } from '@/api/thing/index'
import { reply, getReplyById, deleteReplyById } from "@/api/comment/reply";
import { formatDate, commentTimeFormat } from "@/utils/lib/date";
import { computed, defineAsyncComponent, reactive } from "vue";
import Comment from "./components/comment/index.vue";
import ThingCardSkeleton from "@/components/ThingCardSkeleton/index.vue";
import { useUserStore } from "@/store/modules/user";



const userStroe = useUserStore();

const route = useRoute();
console.log(route);

const ThingCard = defineAsyncComponent(
	() => import("@/components/ThingCard/index.vue")
);



const visuallyData = computed(() => {

	let curObj = pageData.thingInfo
	let curLookCount: number | undefined = curObj?.look_count
	if (typeof curLookCount === undefined) {
		curLookCount = 1
	} else {
		(curLookCount as number)++
	}
	return {
		id: Number(route.params.id),
		look_count: curLookCount
	}
})


const pageData = reactive({
	init: false,
	thingInfo: {} as Record<string, any>,
	commentList: [] as any,
	replyList: [] as any,
	commentRef: null,
});

const thingCommentList = computed(() => {
	let list = JSON.parse(JSON.stringify(pageData.commentList));
	list.forEach((item) => {
		item.reply = [];
	});

	pageData.replyList.forEach((replyItem) => {
		list.forEach((commentItem) => {
			if (commentItem.id === replyItem.commentId) {
				commentItem.reply.push(replyItem);
			}
		});
	});
	return list;
});


// 获取启事评论
const getThingComment = async () => {
	try {
		const res = await getCommentById({
			id: Number(route.params.id),
		});

		pageData.commentList = res.data.data.sort(
			(a, b) => new Date(b.DATE).getTime() - new Date(a.DATE).getTime()
		);
		pageData.commentList.forEach((item) => {
			item.DATE = commentTimeFormat(item.DATE);
		});
		console.log("pageData.commentList", pageData.commentList);
	} catch (error) {
		return Promise.reject(error);
	}
};
// 获取启事回复
const getThingReply = async () => {
	try {
		const res = await getReplyById({
			id: Number(route.params.id),
		});

		pageData.replyList = res.data.data.sort(
			(a, b) => new Date(a.DATE).getTime() - new Date(b.DATE).getTime()
		);
		pageData.replyList.forEach((item) => {
			item.DATE = commentTimeFormat(item.DATE);
		});
		console.log("pageData.replyList", pageData.replyList);
	} catch (error) {
		return Promise.reject(error);
	}
};

/**
 * 获取当前启事的信息
 */
const getThingDetail = async () => {
	try {
		const data = {
			id: Number(route.params.id)
		}
		const res = await getThingInfoById(data)
		if (res.data.code === 200) {
			pageData.thingInfo = res.data.data[0]
			console.log('pageData.thingInfo',pageData.thingInfo);
			
		}
	} catch (err) {
		return Promise.reject(err)
	}
}

// 初始化数据
const initData = async () => {
	try {
		await getThingDetail()
		await getThingComment();
		await getThingReply();
		pageData.init = true;
	} catch (error) {
		return Promise.reject(error);
	}
};
// 提交评论
const commitComment = async (value: string) => {
	console.log(value);
	try {
		let data = {
			DATE: formatDate(new Date()),
			ownerId: Number(route.params.id),
			fromId: userStroe.info.user_id,
			content: value,
		};
		await comment(data);
		await getThingComment();
		await getThingDetail()
	} catch (error) {
		return Promise.reject(error);
	}
};

// 提交回复
const commitReply = async (data: Record<string, any>) => {
	console.log(data);

	try {
		let content = data.inputReply.includes("@")
			? data.inputReply.split(" ")[1]
			: data.inputReply;
		const dataObj = {
			commentId: data.id,
			DATE: formatDate(new Date()),
			ownerId: Number(route.params.id),
			fromId: userStroe.info.user_id,
			content,
			toId: data.userReply.toId,
			toAvatar: data.userReply.toAvatar,
		};
		console.log(dataObj);

		await reply(dataObj);
		await getThingReply();
		await getThingDetail()
	} catch (error) {
		return Promise.reject(error);
	}
};

// 根据评论id删除评论
const deleteComment = async (id: number) => {
	try {
		await deleteCommentById({
			id,
		});
		await getThingDetail()
		await getThingComment();

		
	} catch (error) {
		return Promise.reject(error);
	}
};

// 根据回复id删除回复
const deleteReply = async (id: number) => {
	// console.log(id);

	try {
		await deleteReplyById({
			id,
		});
		await getThingDetail()
		await getThingReply();
	} catch (error) {
		return Promise.reject(error);
	}
};

initData();
</script>

<template>
	<div class="box" v-buried="visuallyData.id" :visually-data="JSON.stringify(visuallyData)" >
		<div class="title-box">
			<p class="title">详情</p>
		</div>
		<div class="detail-box">
			<Suspense>
				<template #default>
					<div>
						<ThingCard
							:thingList="[{...pageData.thingInfo}]" />
					</div>
				</template>

				<template #fallback>
					<div>
						<ThingCardSkeleton />
					</div>
				</template>
			</Suspense>
		</div>
		<!-- 评论区 -->
		<div class="comment-box">
			<div class="comment-title-box">
				<p class="comment-title">评论</p>
			</div>
			<div class="loading" v-if="!pageData.init">
				<Loading />
			</div>

			<Comment v-else :comments="thingCommentList" @comment="commitComment" @reply="commitReply"
				@deleteComment="deleteComment" @deleteReply="deleteReply" />
		</div>
	</div>
</template>

<style lang="less" scoped>
@import "@/styles/mixin.less";

.box {
	border: 2px solid #ccc;
	// width: 900px;
	margin: 0 100px;

	.title-box {
		height: 50px;
		border-bottom: 2px solid #ccc;
		padding-left: 20px;
		.flex(row, flex-start, center);

		.title {
			color: rgb(3, 180, 170);
			font-weight: bold;
			font-size: 20px;
		}
	}

	.detail-box {
		.flex(row, center, center);
	}

	.comment-box {
		padding: 10px 135px;

		.comment-title-box {
			margin-bottom: 10px;

			.comment-title {
				font-weight: bold;
				font-size: 20px;
			}
		}

		.loading {
			.flex(row, center, center);
		}
	}
}
</style>
